
from functools import wraps
from rest_framework import status
from rest_framework.response import Response

from user.models import UserModel
from Efficient.settings import SECRET_KEY

import datetime
import jwt

# def redis_conn():


# 生成token
class MyJwt:

    def encode_time(self,userinfo):
        payload = {
            "exp": int((datetime.datetime.now() + datetime.timedelta(seconds=60 * 60 * 24)).timestamp()),
            'data': userinfo
        }
        encodeed_jwt = jwt.encode(payload, SECRET_KEY, algorithm='HS256')

        return encodeed_jwt

    # 生成token
    def encode(self,userinfo):

        encoded_jwt = jwt.encode(userinfo, SECRET_KEY, algorithm='HS256')

        return encoded_jwt

    # 解密方法
    def decode(self,token):

        decoded_json = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])

        return decoded_json

# 用户鉴权 校验token
def check_login(func):
    def wrapper(self,request,*args,**kwargs):
        token = request.headers.get('Authorization')
        print('装饰器接收前端头部的token',token)
        if token == None:
            return Response({'code': 502, 'msg': '没有token'})
        payload = MyJwt().decode(token)
        print('装饰器解码后的token',payload)

        if type(payload) == dict:
            id = payload.get('id')
            user = UserModel.objects.get(id=id)
            request.user = user
            #
            users = UserModel.objects.filter(id = payload['id']).first()
            self._cuser = users
            return func(self,request,*args,**kwargs)
        else:
            return Response({'code':502,'msg':'未登录'})

    return wrapper
